package com.AnywheeBt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.AnywheeBt.BtCallBack.BroadcastMain;
import com.AnywheeBt.PbapClient.utils.BTConfig;
import com.AnywheeBt.adapter.ContactAdapter;
import com.AnywheeBt.bean.AiosContacts;
import com.AnywheeBt.bean.BtContact;
import com.AnywheeBt.bean.ContactInfo;
import com.aispeech.aios.client.AIOSContactsNode;
import com.google.gson.Gson;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.WindowManager;
import android.view.View.OnClickListener;

public class PbList extends Activity {
	private static final String TAG = "PbList";
	private ListView mPbListView;
	private ContactAdapter mPbAdapter;	
	private ArrayList<BtContact> contacts;
	private List<ContactInfo> mAiosContacts = null;
	private DatabaseHelper mDatabaseHelper;
	private TextView  txTitle;
	private Button mDelBtn;
//	private Button mSyncBtn;
	private Button mCallBtn;
//	private Button mBackBtn;
	
	private Button mMusicBtn;
	private Button mCallRecordBtn;
	private Button mKeybordBtn;
	
	private PbCallList pb_list = new PbCallList();
	private BroadcastMain receiver_pb;	
	ProgressDialog progressDialog = null; 
	private MainHandler mHandler = new MainHandler();
	
	private final static int UPDATE_NUMBER = 0;
	private String mCurrentSelNum = "";
	
	public 	class BroadcastMain extends BroadcastReceiver {    
	    @Override  
	    public void onReceive(Context context, Intent intent) { 
	    	String PbList_msg = intent.getStringExtra("Pb");
	    	
	        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
			ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
			String musciname = cn.getClassName();
			
			if (PbList_msg.equals("1")) {
				if(progressDialog != null)
					progressDialog.dismiss();
				updateNumber();
				Toast.makeText(PbList.this,getResources().getString(R.string.simultaneous_completion), Toast.LENGTH_LONG).show();
			}else if (PbList_msg.equals("2") && musciname.equals("com.AnywheeBt.PbList")) {
				//progressDialog.dismiss();
				//Toast.makeText(PbList.this,getResources().getString(R.string.sync_again), Toast.LENGTH_LONG).show();
			}
	    } 
	} 
	
	public void SyncDelDialog( final boolean bMode)	{ 
		AlertDialog.Builder builder = new Builder(this);
		if(bMode) {
			builder.setTitle(getResources().getString(R.string.dlg_sync_title));
			builder.setMessage(getResources().getString(R.string.dlg_sync_msg));			
		} else {
			builder.setTitle(getResources().getString(R.string.dlg_del_pb_title));
			builder.setMessage(getResources().getString(R.string.dlg_del_pb_msg));						
		}
		builder.setNegativeButton(R.string.dlg_yes,new DialogInterface.OnClickListener() {			
			public void onClick(DialogInterface dialog, int which) {				
				pb_list.DeleteListFile(PbCallList.BT_PB_TEMP);
				pb_list.DeleteListFile(PbCallList.BT_PB_LIST);
					if (bMode) {
						if (SzhBAction.GetBtState() == true) {
							SzhBAction.getPbap();
							dialog.dismiss();
							PbCallList.isDelete = true;
							onProgressDialog();
						} else {
							Toast.makeText(PbList.this,getResources().getString(R.string.msg_connect_error), Toast.LENGTH_LONG).show();
						}
					} else {
						PbCallList.isDelete = false;
						dialog.dismiss();
						if (contacts.size() > 0) {
			                mDatabaseHelper.delAllNumber();
			                updateNumber();
            			}
						Toast.makeText(PbList.this,getResources().getString(R.string.delete_contact), Toast.LENGTH_LONG).show();
					}
					
			}
	});
		builder.setPositiveButton(R.string.dlg_no, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {				
				dialog.dismiss();
			}
		});
		builder.create().show();
	} 
	
	protected void onProgressDialog() {
        progressDialog = new ProgressDialog(PbList.this);  						
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  	
        progressDialog.setTitle(getString(R.string.contact_synchronous));        
        progressDialog.setMessage(getString(R.string.waitcontactsynchronous));         
        progressDialog.setIcon(R.drawable.bto_synchronous);         
        progressDialog.setIndeterminate(false);          				   
        progressDialog.setCancelable(true);            			  
        progressDialog.setButton(getString(R.string.cancle),new SureButtonListener()); 
        progressDialog.show();										      
		Thread thread = new Thread() {
			public void run() {
//				try{
				progressDialog.setCancelable(false);
//				} catch 
//				(InterruptedException e) {
//					e.printStackTrace();
//				}
////				proDialog.dismiss();
////				finish();
			}
		};
		thread.start();
	}
	private class SureButtonListener implements android.content.DialogInterface.OnClickListener{  
        public void onClick(DialogInterface dialog, int which) {  
			dialog.cancel();      }  
	}

	@Override
    public void onCreate(Bundle savedInstanceState)   {
        super.onCreate(savedInstanceState); 
        Log.i(TAG, "onCreate");
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);        
        setContentView(R.layout.contact);   
		
        receiver_pb = new BroadcastMain();
		IntentFilter filter = new IntentFilter();
        filter.addAction("com.AnywheeBt.PbList");
        getApplicationContext().registerReceiver(receiver_pb, filter);


		mDatabaseHelper = DatabaseHelper.getDatabaseHelper(getBaseContext());
		contacts =  new ArrayList<BtContact>();
		contacts = mDatabaseHelper.queryAllContacts();
		mAiosContacts = mDatabaseHelper.getAiosContacts();
		
        //*pb_list.ChangePbList();
        //*pb_list.get_list(PbCallList.BT_PB_LIST);               
        updateNumber();
		
        txTitle = (TextView)findViewById(R.id.pb_list_cnt);
        mPbListView = (ListView)findViewById(R.id.pb_list_view);
		mPbAdapter= new ContactAdapter(getBaseContext(), contacts, R.layout.pb_listview);					
		mPbListView.setAdapter(mPbAdapter);		
		
		mDelBtn = (Button)this.findViewById(R.id.pl_list_contact_del);	
//		mSyncBtn = (Button)this.findViewById(R.id.pl_list_download);
		mCallBtn = (Button)this.findViewById(R.id.pl_list_dail);
//		mBackBtn = (Button)this.findViewById(R.id.pl_list_back);
		
		mMusicBtn = (Button)this.findViewById(R.id.btn_music);
		mCallRecordBtn = (Button)this.findViewById(R.id.btn_callrecord);
		mKeybordBtn = (Button)this.findViewById(R.id.btn_keyboard);
		
//		mBackBtn.setOnClickListener(new View.OnClickListener(){
//			public void onClick(View v) {
//				onBackPressed();
//			}			
//		});
				
		mDelBtn.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				SyncDelDialog(false);
			}			
		});
		
//		mSyncBtn.setOnClickListener(new View.OnClickListener(){
//			public void onClick(View v) {
//				SyncDelDialog(true);
//			}			
//		}); 
		
		mCallBtn.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				//
				SzhBAction.CallPhone(mCurrentSelNum);
			}			
		}); 
		
		mCallRecordBtn.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				Intent intent = new Intent(PbList.this, BtCallList.class);
				startActivity(intent);
			}			
		});
		
		mKeybordBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
              SyncDelDialog(true);
			}			
		});
		
		mMusicBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(PbList.this, BtMusic.class);
				startActivity(intent);
			}
		});
		
		//
		mPbListView.setOnItemClickListener( new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
				mPbAdapter.setSelectItem(arg2);  
				mPbAdapter.notifyDataSetChanged();
				TextView tv = (TextView)arg1.findViewById(R.id.pb_text);
				String strBtNum=(String)tv.getText();
				if( strBtNum !="") {	
					mCurrentSelNum = strBtNum;
					SzhBAction.CallPhone(strBtNum);
				}	
			}			
		});
		if(PbCallList.isSync != 0){
			if(PbCallList.isSync == 1){
				SyncDelDialog(true);
			}else if(PbCallList.isSync == 2){
				SyncDelDialog(false);
			}
		}
    } 	
	@Override  
	protected void onDestroy() {
		Log.i(TAG,"onDestroy");		
	    super.onDestroy();
		PbCallList.isSync = 0;
		getApplicationContext().unregisterReceiver(receiver_pb);
    } 

	//
	private void updateNumber() {
        new Thread() {
            public void run() {
                contacts = mDatabaseHelper.queryAllContacts();
                mAiosContacts = mDatabaseHelper.getAiosContacts();
                mHandler.sendEmptyMessageDelayed(UPDATE_NUMBER, 500);
//                Gson gson = new Gson();
//                String aiosContactStr = gson.toJson(mAiosContacts);
//                //Test By Yanglin Begin
//                
//                Log.e("=======Yanglin=======", aiosContactStr);
//                //Test By Yanglin End
//                sendSyncContactBroadcast(aiosContactStr);
                postContact();
            }
        }.start();
    }
	
    //发送蓝牙电话信息到aios
    private void postContact(){
    	//
        AIOSContactsNode.getInstance().start();
        AIOSContactsNode.getInstance().postData(mAiosContacts.toString());

        Log.e("=======Yanglin=======", mAiosContacts.toString());
    }
	
	private void sendSyncContactBroadcast(String str){
        Intent intent = new Intent(BTConfig.AIOS_BT_CONTACTS_SYNC);
        intent.putExtra("finished", "0");
        intent.putExtra("ContactInfoList", str);
        this.sendBroadcast(intent);
//        intent.putExtra("finished", "1");
//        intent.putExtra("ContactInfoList", "");
//        this.sendBroadcast(intent);
	}
	
	//
	private class MainHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            switch (msg.what) {
            case UPDATE_NUMBER:
                mPbAdapter.setDataChange(contacts);
				txTitle.setText(getResources().getText(R.string.pb_list) +"   "+ contacts.size());
				
                break;
            //case WHAT_DIALOG_OVERTIME:
            	//disProgressDialog();
            //	break;
            default:
                break;
            }
        }
    }
	
	//
	public  ArrayList<HashMap<String, Object>> CallListData() {
		ArrayList<HashMap<String, Object>> mListtem = new ArrayList<HashMap<String, Object>>();
		int nTotal=pb_list.GetListSize();
		if( nTotal>0 )
			txTitle.setText(getResources().getText(R.string.pb_list) +"   "+nTotal);
		for(int i = 0; i < nTotal; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();		
			map.put("pb_name",pb_list.GetListName(i) );
//			map.put("item_name", "");
			map.put("pb_text", pb_list.GetListNum(i));			
//			map.put("item_image", R.drawable.bt_pb_img1);
			mListtem.add(map);				
		}		
		return mListtem;
	}	      
}


